package org.clever.arkdemo.sms.common.infrastructure.adapter.tencent;

import com.alibaba.fastjson.JSON;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20190711.models.SendStatus;
import io.micrometer.common.util.StringUtils;
import org.clever.arkdemo.sms.common.domain.dto.SmsMessage;
import org.clever.arkdemo.sms.common.domain.exception.SmsException;
import org.clever.arkdemo.sms.common.domain.service.SmsService;
import org.clever.arkdemo.sms.common.domain.vo.SmsSendResult;
import org.clever.arkdemo.sms.common.infrastructure.config.SmsProperties;

import java.util.*;

/**
 * 腾讯云短信服务
 */
public class TencentSmsService implements SmsService {

    private final SmsProperties properties;
    private final SmsClient client;

    public TencentSmsService(SmsProperties properties) {
        this.properties = properties;
        String region = properties.getRegion();
        region = region == null ? "" : region;

        Credential credential = new Credential(properties.getAccessKeyId(), properties.getAccessKeySecret());
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint(properties.getEndpoint());
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        this.client = new SmsClient(credential, region, clientProfile);
    }

    @Override
    public SmsSendResult sendSms(SmsMessage smsMessage) {
        Set<String> phones = smsMessage.getPhones();
        String templateId = smsMessage.getTemplateId();
        List<String> params = smsMessage.getParams();
        if (phones.isEmpty()) {
            throw new SmsException("手机号不能为空");
        }
        if (StringUtils.isBlank(templateId)) {
            throw new SmsException("模板ID不能为空");
        }

        SendSmsRequest req = new SendSmsRequest();
        if (params != null && !params.isEmpty()) {
            req.setTemplateParamSet(params.toArray(new String[0]));
        }
        req.setPhoneNumberSet(phones.toArray(new String[0]));
        req.setTemplateID(templateId);
        req.setSign(properties.getSignName());
        req.setSmsSdkAppid(properties.getSdkAppId());
        try {
            SendSmsResponse resp = client.SendSms(req);
            for (SendStatus sendStatus : resp.getSendStatusSet()) {
                if (!"Ok".equals(sendStatus.getCode())) {
                    return new SmsSendResult(1, sendStatus.getMessage(), JSON.toJSONString(resp));
                }
            }
            return new SmsSendResult(0, "发送成功", JSON.toJSONString(resp));
        } catch (Exception e) {
            throw new SmsException(e.getMessage());
        }
    }
}
